package com.huanf.media.api;

import com.huanf.domain.dto.UploadFileParamsDto;
import com.huanf.media.service.MediaFilesService;
import com.xuecheng.base.enums.CourseEnum;
import com.xuecheng.base.model.RestResponse;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author Administrator
 */

@Api(value = "大文件上传接口", tags = "大文件上传接口")
@Slf4j
@RestController
public class BigFilesController {

    @Autowired
    MediaFilesService mediaFilesService;


    @ApiOperation(value = "上传文件检查")
    @PostMapping("/upload/checkfile")
    public RestResponse<Boolean> checkFile(@RequestParam String fileMd5) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return mediaFilesService.checkFile(fileMd5);
    }

    @ApiOperation(value = "分块文件上传前检查分块")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkChunk(@RequestParam("fileMd5") String fileMd5, @RequestParam("chunk") Integer chunk) {
        return mediaFilesService.checkChunk(fileMd5, chunk);
    }
    @ApiOperation(value = "上传分块文件")
    @PostMapping("/upload/uploadchunk")
    public RestResponse uploadChunk(@RequestParam("file")MultipartFile file, @RequestParam("fileMd5") String fileMd5, @RequestParam("chunk") Integer chunk) throws IOException {
        //拿到了file data这个文件目前存在服务器内存中
        File tempFile = File.createTempFile("minio",".temp");
        file.transferTo(tempFile);
        //取得绝对路径
        String absolutePath = tempFile.getAbsolutePath();
        return mediaFilesService.uploadChunk(fileMd5,chunk,absolutePath);
    }

    @ApiOperation(value = "合并分块文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergeChunks(@RequestParam("fileMd5") String fileMd5,
                                    @RequestParam("fileName") String fileName,
                                    @RequestParam("chunkTotal") Integer chunkTotal) {
        Long companyId = 1232141425L;
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        uploadFileParamsDto.setFilename(fileName);
        uploadFileParamsDto.setTags(CourseEnum.MINIO_TYPE_VIDEO.getValue());
        uploadFileParamsDto.setFileType(CourseEnum.MINIO_TYPE_VIDEO.getCode());
        return mediaFilesService.mergeChunks(companyId,fileMd5,chunkTotal,uploadFileParamsDto);
    }
}
